package com.fingard.dsp.bank.directbank.zyb02;

import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.BankConfig;
import com.fingard.dsp.bank.directbank.allinpay02.util.SybUtil;
import com.fingard.dsp.bank.directbank.bankInterface.IBalance;
import com.fingard.dsp.bank.reqrespobj.balance.Req7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.Req7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsBalDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class ZYB02Balance extends ZYB02Base implements IBalance {

    @Override
    public RetAts7506BalQry d_7506_BalQry(Req7506BalQry p_req7506) throws Exception {
        String seqNumberStart = getBankConfig().getMapValueByKey("Sys_Head","CONSUMER_ID")+reqHeader.corporation;
        //说明：中原银行项目查余额没有批量的情况，所以这里先把批量的isBatch作为查询组织机构代码证的标志
        //开户的时候调用批量余额查询，得到组织机构代码证，如果和系统中的组织代码一致则允许开户，否则不允许开户
        if(p_req7506.isBatch) {
            return queryOrgCode(p_req7506);
        }
        //余额查询返回ATS的对象
        RetAts7506BalQry retAts = new RetAts7506BalQry(p_req7506.reqHeader);
        //写返回ATS的统一头部信息
        retAts.writeStart();
        try {
            //赋值通用参数
            ZYB02Header bankHeader = new ZYB02Header();
            //bankHeader.SEQ_NO = reqHeader.transSeqID;
            //bankHeader.SEQ_NO = createBankSerialNumber(reqHeader.bankCode,reqHeader.transType,reqHeader.transSeqID);
            bankHeader.SEQ_NO = seqNumberStart+reqHeader.transSeqID;
            bankHeader.TRAN_CODE = getBankConfig().getMapValueByKey("TRANS_CODE", "BALANCE");
            String transTime = p_req7506.reqHeader.transTime;
            bankHeader.TRAN_DATE = Format.Date8Format.format(DateHelper.convertToDateExtra(transTime));
            bankHeader.TRAN_TIMESTAMP = Format.Time9Format.format(DateHelper.convertToDateExtra(transTime));
            bankHeader.USER_IP = getIpInfoMap(p_req7506.getOriReqXml()).get("userIP");
            bankHeader.SERVER_IP = getIpInfoMap(p_req7506.getOriReqXml()).get("serverIP");
            //发银行报文的XML对象
            XmlTextWriter xmlWriter = new XmlTextWriter();
            xmlWriter.autoFormat = false;
            //写入通用的头部节点
            writeCommonHeader(xmlWriter, bankHeader);

            xmlWriter.writeElementString("BASE_ACCT_NO", p_req7506.reqHeader.ownAct);
            xmlWriter.writeElementString("CCY", convertCurToBank("1"));
            xmlWriter.writeElementString("DEPOSIT_TYPE", "C");

            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if(tmpStrRet[0].length() == 0){
                StringBuilder tmpSbMsg = new StringBuilder();

                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);

                if(tmpBkReader != null){
                    String tmpStatus = tmpBkReader.getFirstText("/Reply_Msg/Sys_Head/RET_STATUS");
                    String ret_code = tmpBkReader.getFirstText("/Reply_Msg/Sys_Head/RET_ARRAY/Row/RET_CODE");
                    String tmpStatusText = tmpBkReader.getFirstText("/Reply_Msg/Sys_Head/RET_ARRAY/Row/RET_MSG");
                    if(tmpStatus != null && tmpStatus.equals(TMPSTATUS)){
                        RetAtsBalDetail tmpRetDetail = new RetAtsBalDetail();

                        if(ret_code != null && ret_code.equals(RET_CODE)){
                            tmpRetDetail.actNum = tmpBkReader.getFirstText("/Reply_Msg/Body/ACCT_ARRAY/Row/BASE_ACCT_NO");
                            tmpRetDetail.respCode = "0";
                            tmpRetDetail.availBal = tmpBkReader.getFirstText("/Reply_Msg/Body/ACCT_ARRAY/Row/AVAILABLE_BAL");
                            //tmpRetDetail.currBal = tmpBkReader.getFirstText("/Reply_Msg/Body/ACCT_ARRAY/Row/ACTUAL_BAL");
                            tmpRetDetail.currBal = tmpBkReader.getFirstText("/Reply_Msg/Body/ACCT_ARRAY/Row/LEDGER_BAL");
                        } else{
                            tmpRetDetail.respCode = "-1";
                            tmpRetDetail.respInfo = ret_code + "-" + tmpStatusText;
                        }
                        retAts.writeRetDetail(tmpRetDetail, p_req7506.isBatch);
                    } else{
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo(tmpStatusText);
                    }
                }
                else{
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpSbMsg.toString());
                }
            }
            else{
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpStrRet[1]);
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAts7505HisBalQry d_7505_BalQry(Req7505HisBalQry p_req7505) throws Exception {
        return null;
    }

    /**
     * 查询组织机构代码证
     * @param p_req7506
     * @return
     * @throws Exception
     */
    private RetAts7506BalQry queryOrgCode(Req7506BalQry p_req7506) throws Exception {
        String seqNumberStart = getBankConfig().getMapValueByKey("Sys_Head","CONSUMER_ID")+reqHeader.corporation;
        //返回ATS的对象
        RetAts7506BalQry retAts = new RetAts7506BalQry(p_req7506.reqHeader);
        //写返回ATS的统一头部信息
        retAts.writeStart();
        String client_no = "";
        String orgCode = "";
        try {
            //赋值通用参数
            ZYB02Header bankHeader = new ZYB02Header();
            //bankHeader.SEQ_NO = reqHeader.transSeqID;
            //bankHeader.SEQ_NO = createBankSerialNumber(reqHeader.bankCode,reqHeader.transType,reqHeader.transSeqID);
            bankHeader.SEQ_NO = seqNumberStart+reqHeader.transSeqID;
            bankHeader.TRAN_CODE = getBankConfig().getMapValueByKey("TRANS_CODE", "BALANCE");
            String transTime = p_req7506.reqHeader.transTime;
            bankHeader.TRAN_DATE = Format.Date8Format.format(DateHelper.convertToDateExtra(transTime));
            bankHeader.TRAN_TIMESTAMP = Format.Time9Format.format(DateHelper.convertToDateExtra(transTime));
            bankHeader.USER_IP = getIpInfoMap(p_req7506.getOriReqXml()).get("userIP");
            bankHeader.SERVER_IP = getIpInfoMap(p_req7506.getOriReqXml()).get("serverIP");
            //发银行报文的XML对象
            XmlTextWriter xmlWriter = new XmlTextWriter();
            xmlWriter.autoFormat = false;
            //写入通用的头部节点
            writeCommonHeader(xmlWriter, bankHeader);

            xmlWriter.writeElementString("BASE_ACCT_NO", p_req7506.reqHeader.ownAct);
            xmlWriter.writeElementString("CCY", convertCurToBank("1"));
            xmlWriter.writeElementString("DEPOSIT_TYPE", "C");

            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpStatus = tmpBkReader.getFirstText("/Reply_Msg/Sys_Head/RET_STATUS");
                    String ret_code = tmpBkReader.getFirstText("/Reply_Msg/Sys_Head/RET_ARRAY/Row/RET_CODE");
                    String tmpStatusText = tmpBkReader.getFirstText("/Reply_Msg/Sys_Head/RET_ARRAY/Row/RET_MSG");
                    RetAtsBalDetail tmpRetDetail = new RetAtsBalDetail();
                    if (tmpStatus != null && tmpStatus.equals(TMPSTATUS)) {
                        if (ret_code != null && ret_code.equals(RET_CODE)) {
                            client_no = tmpBkReader.getFirstText("/Reply_Msg/Body/ACCT_ARRAY/Row/CLIENT_NO");
                        }
                    }
                }
            }
            if(StringHelper.isNullOrEmpty(client_no)) {
                throw new Exception("没有查询到客户号!");
            }

            WriteBankLogLn("查询到的客户号为："+client_no);
            //根据客户号查询组织机构代码证
            bankHeader.SEQ_NO = bankHeader.SEQ_NO+ SybUtil.getValidatecode(2);
            bankHeader.TRAN_CODE = getBankConfig().getMapValueByKey("TRANS_CODE", "ORGCODEQUERY");
            bankHeader.USER_IP = getIpInfoMap(p_req7506.getOriReqXml()).get("userIP");
            bankHeader.SERVER_IP = getIpInfoMap(p_req7506.getOriReqXml()).get("serverIP");
            XmlTextWriter xmlWriterOrg = new XmlTextWriter();
            xmlWriterOrg.autoFormat = false;
            writeCommonHeader(xmlWriterOrg,bankHeader);

            xmlWriterOrg.writeElementString("OPTION", "01");
            xmlWriterOrg.writeElementString("CLIENT_NO", client_no);

            xmlWriterOrg.writeEndElement();
            xmlWriterOrg.writeEndDocument();

            String[] result = sendToBank(xmlWriterOrg.toXmlString());
            if (result[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(result[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpStatus = tmpBkReader.getFirstText("/Reply_Msg/Sys_Head/RET_STATUS");
                    String ret_code = tmpBkReader.getFirstText("/Reply_Msg/Sys_Head/RET_ARRAY/Row/RET_CODE");
                    String tmpStatusText = tmpBkReader.getFirstText("/Reply_Msg/Sys_Head/RET_ARRAY/Row/RET_MSG");
                    if (tmpStatus != null && tmpStatus.equals(TMPSTATUS)) {
                        RetAtsBalDetail tmpRetDetail = new RetAtsBalDetail();
                        if (ret_code != null && ret_code.equals(RET_CODE)) {
                            while (tmpBkReader.read("/Reply_Msg/Body/DOCUMENT_ARRAY/Row")) {
                                if("201".equals(tmpBkReader.readedXElement.getSingleText("GOVE_IDEN_NUM_TYPE_CODE"))) {
                                    orgCode = tmpBkReader.readedXElement.getSingleText("GOVE_IDEN_NUM");
                                    break;
                                }
                            }
                            tmpRetDetail.actNum = orgCode;
                            tmpRetDetail.respCode = "0";
                            tmpRetDetail.respInfo = orgCode;
                            tmpRetDetail.availBal = "0.0";
                            tmpRetDetail.currBal = "0.0";
                        } else {
                            tmpRetDetail.respCode = "-1";
                            tmpRetDetail.respInfo = ret_code + "-" + tmpStatusText;
                        }
                        retAts.writeRetDetail(tmpRetDetail, p_req7506.isBatch);
                    } else {
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo(tmpStatusText);
                    }
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpSbMsg.toString());
                }
            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpStrRet[1]);
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
        }
        retAts.writeEnd();
        return retAts;
    }
}
